import { createContext, useState, useContext } from "react";


// 1. 创建上下文对象, 内部可以传入初始值
const MyContext = createContext()

// 2. 初始化上下文的值
function UseConetxtData({ children }) {
  const [person, setPerson] = useState({
    name: '夏天',
    age: 18
  })

  const addAge = () => {
    setPerson({ ...person, age: person.age + 1 })
  }
  const changeName = (name) => {
    setPerson({ ...person, name })
  }
  const clearPerson = () => {
    setPerson({})
  }

  return (
    // <MyContext.Provider value={person, addAge, changeName, clearPerson}>
    <div>
      <span>姓名:{person.name}----年龄: {person.age}</span>
      <MyContext.Provider value={{ person, addAge, changeName, clearPerson }}>
        {children}
      </MyContext.Provider>
    </div>
  )
}

export default function UseConetxtDemo() {

  return (
    <>
      <h1>useContext的用法</h1>
      <UseConetxtData children={<Son />} />
    </>
  )
}

// 子组件
const Son = () => {
  const { person, addAge, changeName, clearPerson } = useContext(MyContext)
  return (
    <div>
      hello,我模拟的是子孙组件,收到上下文中的数据
      <div>{person.name} ---{person.age}</div>
      <button onClick={addAge}>修改年龄</button>
      <button onClick={() => changeName('周杰伦')}>修改名字</button>
      <button onClick={clearPerson}>清空信息</button>
    </div>
  )
}